// app.js
const { apiMusics } = require('./cabin.config')
App({
  onLaunch() {
    // 获取系统信息
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;  
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })
    wx.showLoading({
      title: '拉取小屋信息',
    })
    this.promiseMusic()
  },
  promiseMusic () {
    let promiseArr = [];
    for (let index = 0, len = apiMusics.length; index < len; index++) {
      const api = apiMusics[index];
      let promise = new Promise((resolve, reject) => {
        wx.request({
          url: api,
          success: function(res) {
            const { code, data, message} =  res.data
            if (code === 200) {
              resolve(data.spaceEntities)
            } else {
              reject(message || '失败')
            }
          },
          fail: function (error) {
            reject(error)
          }
        })
      })
      promiseArr.push(promise)
    }
    Promise.all(promiseArr).then((res) => {
      this.globalData.musicList = res || []
      if(this.musicCallback && typeof this.musicCallback === 'function') {
        that.musicCallback()
        console.log('musicCallback')
      }
    })
  },
  async getMusics () {
		this.setData({
			userInfo: await app.getUserInfo()
		})
  },
  addMusic (list, url) {
    const temp = this.globalData.musicObj || {}
    if (temp[url] && temp[url].data.length === list.length) return
    temp[url] = list
    this.globalData.musicObj =temp
  },
  getMusicsq () {
    let apiCount = 0
    const that = this
    for (let index = 0, len = apiMusics.length; index < len; index++) {
      const api = apiMusics[index];
      console.log('app-api', api)
      wx.request({
        url: api,
        success(res){
          const { code, data, message} =  res.data
          if (code === 200) {
            that.addMusic(data, api)
          } else {
            wx.showToast({
              title: message,
              icon: 'error'
            })
          }
        },
        complete () {
          debugger
          apiCount++
          if(apiMusics.length === apiCount && that.musicCallback && typeof that.musicCallback === 'function') {
            that.musicCallback()
            console.log('musicCallback')
          }
        }
      })
    }
  },
  globalData: {
  }
})
